﻿using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using UnityEngine.Events;

/// <summary>
/// 资源管理，加载和卸载，路径分为Resources（prefab）和Application.persistentDataPath（assetbundle）
/// </summary>
public class ResMgr : MonoBehaviour
{
    public static ResMgr Instance;

    public static Dictionary<string, AssetBundle> abs = new Dictionary<string, AssetBundle>();

    /// <summary>
    /// 资源服务器地址
    /// </summary>
    string serverRoot = "https://www.ganghood.net.cn/Game/";

    /// <summary>
    /// assetbundle文件的更新地址
    /// </summary>
    string abRoot;
    /// <summary>
    /// AssetBundleManifest
    /// </summary>
    AssetBundleManifest abm = null;

    public void Init(UnityAction unityAction)
    {
        Instance = this;
        abRoot = serverRoot + Util.GetPlatformName(Application.platform) + "/";
        StartCoroutine(LaodABM(unityAction));
    }

    /// <summary>
    /// 加载AssetBundleManifest文件
    /// </summary>
    /// <param name="unityAction"></param>
    /// <returns></returns>
    IEnumerator LaodABM(UnityAction unityAction)
    {
        string platformName = PathMgr.Instance.GetPlatformName(Application.platform);
        string abmPath = "";
        if (PathMgr.Instance.isEditor())
        {
            abmPath = PathMgr.Instance.abStreamingAssetsPathRoot + platformName + ".t";
        }
        else
        {
            abmPath = PathMgr.Instance.abPersistentDataPathRoot + platformName + ".t";
        }
        WWW www = new WWW(abmPath);
        yield return www;
        if (string.IsNullOrEmpty(www.error))
        {
            var bundle = www.assetBundle;
            abm = bundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
            if (unityAction != null)
            {
                unityAction();
            }
            if (bundle != null)
            {
                yield return new WaitForEndOfFrame();
                bundle.Unload(false);
                bundle = null;
            }
            www.Dispose();
            www = null;
        }
        else
        {
            Debug.LogError(string.Format("加载AssetBundleManifest失败:{0}\n{1}", www.url, www.error));
        }
    }

    /// <summary>
    /// 加载
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public void Load(string name, UnityAction<GameObject> action)
    {
        StartCoroutine(LoadAsync(name, action));
    }

    /// <summary>
    /// 加载
    /// </summary>
    /// <param name="name"></param>
    /// <param name="action"></param>
    public void LoadUI(string name, ViewBase panel, UnityAction<GameObject, ViewBase> action)
    {
        StartCoroutine(LoadUIAsync(name, panel, action));
    }

    /// <summary>
    /// 异步加载
    /// </summary>
    /// <param name="name"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    private IEnumerator LoadAsync(string name, UnityAction<GameObject> action)
    {
        GameObject obj = null;
        string filePath = "";
        if (PathMgr.Instance.isEditor())
        {
            filePath = PathMgr.Instance.abStreamingAssetsPathRoot + name + ".t";
        }
        else
        {
            filePath = PathMgr.Instance.abPersistentDataPathRoot + name + ".t";
        }
        Log.Debug("加载AB");
        WWW www = new WWW(filePath);
        yield return www;
        AssetBundle ab = www.assetBundle;
        obj = Instantiate(ab.LoadAsset<GameObject>(name));

        abs.Add(name, ab);
        Unload(name, false);
        Log.Debug("卸载AB");
        ab = null;

        if (action != null && obj != null)
        {
            action(obj);
        }
    }

    /// <summary>
    /// 异步加载
    /// </summary>
    /// <param name="name"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    private IEnumerator LoadUIAsync(string name, ViewBase panel, UnityAction<GameObject, ViewBase> action)
    {
        GameObject obj = null;
        string filePath = "";
        if (PathMgr.Instance.isEditor())
        {
            filePath = PathMgr.Instance.abStreamingAssetsPathRoot + name + ".t";
        }
        else
        {
            filePath = PathMgr.Instance.abPersistentDataPathRoot + name + ".t";
        }
        Log.Debug("加载AB");
        WWW www = new WWW(filePath);
        yield return www;
        AssetBundle ab = www.assetBundle;
        obj = Instantiate(ab.LoadAsset<GameObject>(name));
        obj.name = name;
        abs.Add(name, ab);
        Unload(name, false);
        Log.Debug("卸载AB");
        ab = null;

        if (action != null && obj != null)
        {
            action(obj, panel);
        }
    }

    public void Unload(string name, bool state)
    {
        if (abs.ContainsKey(name))
        {
            abs[name].Unload(state);
            abs.Remove(name);
        }
    }

    public void ClearAll()
    {
        foreach (var ab in abs)
        {
            Unload(ab.Key, true);
        }
    }
}